<?php
/**
 * Author: ChenGuangHui
 * Email：13035809409@163.com
 * Date Time: 2021/8/17 16:59
 */


namespace App\Logic\Doc;


use App\Enums\HttpCode;
use App\Logic\CommLogic;
use App\Logic\Common\BaseLogic;
use App\Models\Document\DocumentAnnex;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;

class DocAnnexLogic extends CommLogic
{
    /**
     * @param array $params
     * @return array
     */
    public function lists($params)
    {
        $list = DocumentAnnex::query()
            ->when($params['doc_id'], function (Builder $query) use ($params) {
                $query->where('doc_id', $params['doc_id']);
            })
            ->orderByDesc('created_at')
            ->get()
            ->toArray();
        foreach ($list as &$item) {
            $item['size'] = formatBytes($item['file_size']);
        }
        return $list;
    }

    /**
     * 文档附件上传
     * @param Request $request
     * @return \App\Models\Model|array|Builder|\Illuminate\Database\Eloquent\Model
     * @throws \App\Exceptions\RJsonError
     */
    public function upload(Request $request)
    {
        $lockName = 'document_upload_' . auth('api')->id();
        $lock = \Cache::lock($lockName, 5);
        abort_if(!$lock->get(), HttpCode::TOO_MANY_REQUESTS, '请勿重复操作！');
        if ($file = $request->file('file')) {
            abort_if(!$file->isValid(), HttpCode::FORBIDDEN, '上传失败！');
            // 调用公共上传模块
            $upload = (new BaseLogic())->upload($file, array(
                'file_path' => '/doc/tmp/',
                'extension' => $file->extension(),
                'original_name' => $file->getClientOriginalName(),
            ));
            $params = [
                'file_size' => $upload['file_size'],
                'file_suffix' => $file->extension(),
                'staffer_id' => auth('api')->id(),
                'original_name' => $upload['original_name'],
                'path' => $upload['file_url'],
                'doc_id' => $request->get('doc_id', 0),
                'hash' => hash_file('md5', $request->file('file'))
            ];
            return DocumentAnnex::query()->create($params);
        }
        return [];
    }

    /**
     * @param $id
     * @return bool|mixed|null
     */
    public function destroy($id)
    {
        $annex = DocumentAnnex::query()->where('id', $id)->first();
        abort_if(empty($annex), HttpCode::FORBIDDEN, '附件不存在！');
        return $annex->delete();
    }
}
